<template>
  <!-- 昵称编辑组件 -->
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <!-- /导航栏 -->
    <div class="field-warp">
      <!-- 修改昵称内容框 -->
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
      <!-- /修改昵称内容框 -->
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  components: {},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      localName: this.value
    }
  },
  computed: {},
  watch: {},
  methods: {
    async onConfirm() {
      // 增加loading 加载状态，防止用户反复点击
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        const localName = this.localName
        if (!localName.length) {
          this.$toast.error('昵称不能为空')
          return
        }
        // 发送参数，请求更新
        await updateUserProfile({
          name: localName
        })
        this.$emit('input', localName) // 更新视图 v-model 方法操作
        this.$toast.success('昵称修改成功') // 提示成功
        this.$emit('close') // 关闭弹出层
      } catch (err) {
        this.$toast('数据获取失败')
      }
    }
  },
  created() {},
  mounted() {}
}
</script>
<style scoped lang="less">
.field-warp {
  padding: 20px;
}
</style>
